package com.dongdong.zhuangji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.dongdong.zhuangji.controller.utils.R;
import com.dongdong.zhuangji.entity.PileData;
import com.dongdong.zhuangji.entity.dto.PagePileDto;
import com.dongdong.zhuangji.entity.dto.TimeForCountCompletedPilesDao;
import com.dongdong.zhuangji.service.PileDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;


@RestController
@RequestMapping("/pileData")
@CrossOrigin//解决跨域问题
public class PileDataController {
    private static final Logger log = LoggerFactory.getLogger(PileDataController.class);
    @Autowired
    private PileDataService pileDataService;

    // 添加数据
    @PostMapping
    public R addPileData(@RequestBody PileData pileData) {
        return new R(pileDataService.save(pileData));
    }

    // 根据 ID 删除数据
    @DeleteMapping("/{id}")
    public R deletePileData(@PathVariable Integer id) {
        return new R(pileDataService.removeById(id));
    }

    // 更新数据
    @PutMapping
    @PreAuthorize("hasAnyAuthority('superadmin')")
    public R updatePileData(@RequestBody PileData pileData) {
        System.out.println(pileData.toString());
        return new R(pileDataService.updateById(pileData));
    }

    // 根据 ID 查询数据
    @GetMapping("/{id}")
    public R getPileDataById(@PathVariable Integer id) {
        return new R(pileDataService.getById(id));
    }
    // 根据 ID 查询数据
    @GetMapping("/pileNumber/{pileNumber}")
    public R getPileDataByPileNumber(@PathVariable String  pileNumber) {
        return new R(pileDataService.getPileDataByPileNumber(pileNumber));
    }

    // 查询所有数据
    @GetMapping
    //@PreAuthorize("hasAuthority('superadmin')")
    public R getAllPileData() {
        return new R(pileDataService.list());
    }

    // 条件查询数据
    @GetMapping("/page/{pageNum}/{pageSize}")
    public R getPileDataByPage(@PathVariable Integer pageNum,
                                            @PathVariable Integer pageSize,String pileNumber, PileData pileData) {
        PagePileDto pagePileDto = new PagePileDto();
        pagePileDto.setPageNum(pageNum);
        pagePileDto.setPageSize(pageSize);
        BeanUtils.copyProperties(pileData, pagePileDto);
        log.info(pagePileDto.toString());
        log.info(pileNumber);
        log.info(pileData.toString());


        // 创建查询条件包装器
        LambdaQueryWrapper<PileData> queryWrapper = new LambdaQueryWrapper<>();

        // 处理字符串类型字段的模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(pileData.getPileNumber()),
                PileData::getPileNumber, pileData.getPileNumber());
        queryWrapper.like(StringUtils.isNotEmpty(pileData.getTestBlockNumber()),
                PileData::getTestBlockNumber, pileData.getTestBlockNumber());

        // 处理数值类型字段的精确查询（如果需要模糊查询数值，可根据业务需求转换为字符串处理）
        queryWrapper.eq(pileData.getMileage() != null,
                PileData::getMileage, pileData.getMileage());
        queryWrapper.eq(pileData.getOffset() != null,
                PileData::getOffset, pileData.getOffset());
        queryWrapper.eq(pileData.getCoordinateX() != null,
                PileData::getCoordinateX, pileData.getCoordinateX());
        queryWrapper.eq(pileData.getCoordinateY() != null,
                PileData::getCoordinateY, pileData.getCoordinateY());
        queryWrapper.eq(pileData.getPileBottomElevation() != null,
                PileData::getPileBottomElevation, pileData.getPileBottomElevation());
        queryWrapper.eq(pileData.getPileTopElevation() != null,
                PileData::getPileTopElevation, pileData.getPileTopElevation());
        queryWrapper.eq(pileData.getPileDiameter() != null,
                PileData::getPileDiameter, pileData.getPileDiameter());
        queryWrapper.eq(pileData.getPileLength() != null,
                PileData::getPileLength, pileData.getPileLength());
        queryWrapper.eq(pileData.getSteelCageLength() != null,
                PileData::getSteelCageLength, pileData.getSteelCageLength());
        queryWrapper.eq(pileData.getOverPouringLength() != null,
                PileData::getOverPouringLength, pileData.getOverPouringLength());
        queryWrapper.eq(pileData.getGroundElevation() != null,
                PileData::getGroundElevation, pileData.getGroundElevation());
        queryWrapper.eq(pileData.getActualPileBottomElevation() != null,
                PileData::getActualPileBottomElevation, pileData.getActualPileBottomElevation());

        // 处理日期类型字段的精确查询（如果需要范围查询等，可根据业务需求调整）
        queryWrapper.eq(pileData.getExcavationTime() != null,
                PileData::getExcavationTime, pileData.getExcavationTime());
        queryWrapper.eq(pileData.getHoleOpeningTime() != null,
                PileData::getHoleOpeningTime, pileData.getHoleOpeningTime());
        queryWrapper.eq(pileData.getHoleCompletionTime() != null,
                PileData::getHoleCompletionTime, pileData.getHoleCompletionTime());
        queryWrapper.eq(pileData.getReinforcementCageLoweringTime() != null,
                PileData::getReinforcementCageLoweringTime, pileData.getReinforcementCageLoweringTime());
        queryWrapper.eq(pileData.getConduitLoweringTime() != null,
                PileData::getConduitLoweringTime, pileData.getConduitLoweringTime());
        queryWrapper.eq(pileData.getPouringTime() != null,
                PileData::getPouringTime, pileData.getPouringTime());

        log.info(pagePileDto.toString());
        Page<PileData> page = new Page<>(pagePileDto.getPageNum(), pagePileDto.getPageSize());
        return new R(pileDataService.page(page,queryWrapper));
    }
   /*   // 分页查询数据
    @GetMapping("/page")
    public Page<PileData> getPileDataByPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                            @RequestParam(defaultValue = "10") Integer pageSize) {
        log.println(pageNum+"====page"+pageSize);
        Page<PileData> page = new Page<>(pageNum, pageSize);
        return pileDataService.page(page);
    }*/


    @GetMapping("/page")
    public R getPileDataByPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            PileData pileData) {
        log.info(pileData.toString());
        LambdaQueryWrapper<PileData> queryWrapper = new LambdaQueryWrapper<>();
        // 处理字符串类型字段的模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(pileData.getPileNumber()),
                PileData::getPileNumber, pileData.getPileNumber());
        queryWrapper.like(StringUtils.isNotEmpty(pileData.getTestBlockNumber()),
                PileData::getTestBlockNumber, pileData.getTestBlockNumber());

        // 处理数值类型字段的精确查询（如果需要模糊查询数值，可根据业务需求转换为字符串处理）
        queryWrapper.eq(pileData.getMileage() != null,
                PileData::getMileage, pileData.getMileage());
        queryWrapper.eq(pileData.getOffset() != null,
                PileData::getOffset, pileData.getOffset());
        queryWrapper.eq(pileData.getCoordinateX() != null,
                PileData::getCoordinateX, pileData.getCoordinateX());
        queryWrapper.eq(pileData.getCoordinateY() != null,
                PileData::getCoordinateY, pileData.getCoordinateY());
        queryWrapper.eq(pileData.getPileBottomElevation() != null,
                PileData::getPileBottomElevation, pileData.getPileBottomElevation());
        queryWrapper.eq(pileData.getPileTopElevation() != null,
                PileData::getPileTopElevation, pileData.getPileTopElevation());
        queryWrapper.eq(pileData.getPileDiameter() != null,
                PileData::getPileDiameter, pileData.getPileDiameter());
        queryWrapper.eq(pileData.getPileLength() != null,
                PileData::getPileLength, pileData.getPileLength());
        queryWrapper.eq(pileData.getSteelCageLength() != null,
                PileData::getSteelCageLength, pileData.getSteelCageLength());
        queryWrapper.eq(pileData.getOverPouringLength() != null,
                PileData::getOverPouringLength, pileData.getOverPouringLength());
        queryWrapper.eq(pileData.getGroundElevation() != null,
                PileData::getGroundElevation, pileData.getGroundElevation());
        queryWrapper.eq(pileData.getActualPileBottomElevation() != null,
                PileData::getActualPileBottomElevation, pileData.getActualPileBottomElevation());

        // 处理日期类型字段的精确查询（如果需要范围查询等，可根据业务需求调整）
        queryWrapper.eq(pileData.getExcavationTime() != null,
                PileData::getExcavationTime, pileData.getExcavationTime());
        queryWrapper.eq(pileData.getHoleOpeningTime() != null,
                PileData::getHoleOpeningTime, pileData.getHoleOpeningTime());
        queryWrapper.eq(pileData.getHoleCompletionTime() != null,
                PileData::getHoleCompletionTime, pileData.getHoleCompletionTime());
        queryWrapper.eq(pileData.getReinforcementCageLoweringTime() != null,
                PileData::getReinforcementCageLoweringTime, pileData.getReinforcementCageLoweringTime());
        queryWrapper.eq(pileData.getConduitLoweringTime() != null,
                PileData::getConduitLoweringTime, pileData.getConduitLoweringTime());
        queryWrapper.eq(pileData.getPouringTime() != null,
                PileData::getPouringTime, pileData.getPouringTime());


        Page<PileData> page = new Page<>(pageNum, pageSize);
        return new R(pileDataService.page(page, queryWrapper));
    }

    // 根据桩基号查询数据
    @GetMapping("/search")
    public R searchPileDataByPileNumber(@RequestParam String pileNumber) {
        QueryWrapper<PileData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pile_number", pileNumber);
        return new R(pileDataService.list(queryWrapper)) ;
    }

    /**
     *  生成
     * @param id
     * @param response
     */
    @GetMapping("/createPouringTable")
    public R createPouringTable(@RequestParam int id, HttpServletResponse response) {
        //下载到客户端
        // pileDataService.createPuringTable(id,response);
        //上传到minio
        System.out.println("2025年6月3日21:38:41=============================>");
        try {
            pileDataService.createPuringTabletoMinio(id, response);
            pileDataService.createPuringTable2toMinio(id, response);
            return new R("操作成功，已经生成表格并上传到minio");
        }catch (Exception e) {
            return new R(false,"统计失败：" + e.getMessage());
        }

    }

    /**
     * 统计已完成浇筑的桩基数量
     * @return 统一返回结果 R，包含统计数量
     */
    @GetMapping("/countCompletedPiles")
    public R countCompletedPiles() {
        try {
            Integer count = pileDataService.countCompletedPiles();
            // 处理可能的 null（数据库无记录时返回 null）
            int result = count != null ? count : 0;
            return new R(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new R("统计失败：" + e.getMessage());
        }
    }


    /**
     * 分页统计已完成浇筑的桩基数量
     * @param pageNum
     * @param pageSize
     * @param timeForCountCompletedPilesDao
     * @return
     */
    @PostMapping("/countCompletedPilesByTime")
    public R countCompletedPilesByTime(@RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestBody TimeForCountCompletedPilesDao timeForCountCompletedPilesDao) {

       // System.out.println("\n++++++++++++++++++++>"+pageNum + "-" + pageSize+timeForCountCompletedPilesDao);

        try {
            return new R(pileDataService.getPileDataByPouringTimeRange(pageNum,pageSize,timeForCountCompletedPilesDao));


        } catch (Exception e) {
            e.printStackTrace();
            return new R("查询失败：" + e.getMessage());
        }
    }

/**
     * 分页统计已完成浇筑的桩基数量
     * @param pageNum
     * @param pageSize
     * @param timeForCountCompletedPilesDao
     * @return
     *//*
    @PostMapping("/creatTableForPileQuantity")
    public R creatTableForPileQuantity(@RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestBody TimeForCountCompletedPilesDao timeForCountCompletedPilesDao, HttpServletResponse response) {

        System.out.println("\n++++++++++++++++++++>"+pageNum + "-" + pageSize+timeForCountCompletedPilesDao);

        try {
            pileDataService.createQuantityTableforPileToMinimo(timeForCountCompletedPilesDao,response);
            return new R(true);
        } catch (Exception e) {
            e.printStackTrace();
            return new R("查询失败：" + e.getMessage());
        }
    }*/

    /**
     *
     * @param pageNum
     * @param pageSize
     * @param startTime
     * @param endTime
     * @param sort
     * @param response
     * @return
     */
    @GetMapping("/createTableForPileQuantity") // 修改为GET请求
    public R createTableForPileQuantity(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "492") Integer pageSize,
            @RequestParam("startTime") Date startTime,  // 直接接收参数
            @RequestParam("endTime") Date endTime,
            @RequestParam(required = false, defaultValue = "false",name = "sort") boolean sort,
            HttpServletResponse response) {

        log.info("生成充电桩数量报表请求 - 分页信息: {}, {}, 时间范围: {} - {}, 排序: {}",
                pageNum, pageSize, startTime, endTime, sort);

        try {
            // 构建查询对象
            TimeForCountCompletedPilesDao query = new TimeForCountCompletedPilesDao();
            query.setStartTime(startTime);
            query.setEndTime(endTime);
            query.setSort(sort);

            // 调用服务层生成报表
            pileDataService.createQuantityTableforPileToMinimo(query, response);

            return new R(true);
        } catch (Exception e) {
            log.error("生成报表失败: {}", e.getMessage());
            return new R(false,"查询失败：" + e.getMessage());
        }
    }

    // 获取当前认证用户
    @GetMapping("/currentUser")
    public R getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return new R(authentication.getName()); // 返回用户名
    }

    // 或通过方法参数直接注入
    @GetMapping("/user")
    public R getUser(Authentication authentication) {
        return new R(authentication.getPrincipal()); // 返回完整用户信息
    }

    // 只有拥有"superadmin"权限的用户可访问
    @PreAuthorize("hasAuthority('superadmin')")
    @GetMapping("/admin-only")
    public R adminOnly() {
        return new R("仅管理员可访问");
    }

    // 允许具有"read:pile"或"write:pile"权限的用户访问
    @PreAuthorize("hasAnyAuthority('read:pile', 'write:pile')")
    @GetMapping("/public")
    public R publicAccess() {
        return new R("有权限的用户可访问");
    }
}    